package com.ruoyi.common.utils;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MSWordPoi4 {
    private static Logger logger = LoggerFactory.getLogger(MSWordPoi4.class);

    /**
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("${t1}", "刘老板");//供方名称
        map.put("${t2}", "刘虎");//供方名称
        map.put("${t3}", "刘大龙");//供方名称
        map.put("${t4}", "1000万");//供方名称
        map.put("${t5}", "2000万");//供方名称
//        模板路径-读取服务器路径
        String srcPath = "D:\\work\\lvshihan.doc";
        testReadwriteWord(srcPath, map);
    }


    public static String testReadwriteWord(String filePath, Map<String, String> map) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        HWPFDocument hdt = null;
        try {
            hdt = new HWPFDocument(in);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Fields fields = hdt.getFields();
        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();
        while (it.hasNext())
        {
            System.out.println(it.next().getType());
        }

        //读取word文本内容
        Range range = hdt.getRange();
        TableIterator tableIt = new TableIterator(range);
        //迭代文档中的表格
        int ii = 0;
        while (tableIt.hasNext()) {
            Table tb = (Table) tableIt.next();
            ii++;
            //迭代行，默认从0开始
            for (int i = 0; i < tb.numRows(); i++) {
                TableRow tr = tb.getRow(i);
                //只读前8行，标题部分
                if (i >= 8) break;
                //迭代列，默认从0开始
                for (int j = 0; j < tr.numCells(); j++) {
                    TableCell td = tr.getCell(j);//取得单元格
                    //取得单元格的内容
                    for (int k = 0; k < td.numParagraphs(); k++) {
                        Paragraph para =  td.getParagraph(k);
                        String s = para.text();
                    } //end for
                }   //end for
            }   //end for
        } //end while
        //System.out.println(range.text());

        // 替换文本内容
        for (Map.Entry<String, String> entry : map.entrySet()) {
            range.replaceText(entry.getKey(), entry.getValue());
        }
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        String fileName = "" + System.currentTimeMillis();
        fileName += ".doc";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("D:\\work\\" + fileName, true);
            hdt.write(ostream);
            out.write(ostream.toByteArray());
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
                ostream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String readwriteWord(Integer type,String filePath, Map<String, Object> map) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        HWPFDocument hdt = null;
        try {
            hdt = new HWPFDocument(in);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Fields fields = hdt.getFields();
        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();
//        while (it.hasNext())
//        {
//            System.out.println(it.next().getType());
//        }

        //读取word文本内容
        Range range = hdt.getRange();
        TableIterator tableIt = new TableIterator(range);
        //迭代文档中的表格
        int ii = 0;
        while (tableIt.hasNext()) {
            Table tb = (Table) tableIt.next();
            ii++;
            //迭代行，默认从0开始
            for (int i = 0; i < tb.numRows(); i++) {
                TableRow tr = tb.getRow(i);
                //只读前8行，标题部分
                if (i >= 8) break;
                //迭代列，默认从0开始
                for (int j = 0; j < tr.numCells(); j++) {
                    TableCell td = tr.getCell(j);//取得单元格
                    //取得单元格的内容
                    for (int k = 0; k < td.numParagraphs(); k++) {
                        Paragraph para = td.getParagraph(k);
                        String s = para.text();
                    } //end for
                }   //end for
            }   //end for
        } //end while
        //System.out.println(range.text());

        // 替换文本内容
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            logger.info("---------------------------"+entry.getValue().toString());
            range.replaceText(entry.getKey(), entry.getValue().toString());
        }
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        String fileName = "" + System.currentTimeMillis() + ".doc";
        FileOutputStream out = null;
        String targetPath = null;
        try {
//            if(type == Constant.FileMakerType.LV_SHI_HAN.getCode()){
//                targetPath = "/usr/local/nginx/html/file_example/lvshihan/";
//            }
//            if(type == Constant.FileMakerType.QI_SU_ZHUANG.getCode()){
//                targetPath = "/usr/local/nginx/html/file_example/qisuzhuang/";
//            }
//            if(type == Constant.FileMakerType.JIE_KUAN.getCode()){
//                targetPath = "C:\\software\\develop\\nginx-1.18.0\\html\\file_example\\";
//            }
            targetPath = "C:\\software\\develop\\nginx-1.18.0\\html\\file_example\\";
            out = new FileOutputStream(targetPath + fileName, true);
            hdt.write(ostream);
            out.write(ostream.toByteArray());
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
                ostream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}